<template>
  <el-dialog v-dialogDrag title="选择机器" width="450px" :visible.sync="params.visible">
    <div class="box1">
      <compTree
        ref="tree"
        :show-search="false"
        :tree-show-checkbox="true"
        :tree-data="treeData"
        :tree-default-checked-keys="treeDefaultCheckedKeys"
      />
    </div>
    <dialog-btn slot="footer" />
  </el-dialog>
</template>

<script>
import { getControlGroupView } from '@/api/core'
import { ParamArr, SQLTable } from '../../../public/js/paramarr'
import Global from '../../../public/js/global'
export default {
  name: 'SelectComputerLayer',
  props: {
    params: {
      type: Object,
      default() {
        return {
          visible: false,
          ids: ''// 需要回显的id
        }
      }
    }
  },
  data() {
    return {
      treeData: [],
      treeDefaultCheckedKeys: []
    }
  },
  created() {
    getControlGroupView(new ParamArr()).then(vPar => {
      var nodes = []
      var nodeMap = new Map()
      // 分组
      var table = new SQLTable(vPar.getTable('k_group'))
      table.first()
      while (!table.eof()) {
        var pnode = Global.getTreeviewPNode(nodeMap, nodes, table.getValueByName('PID'))
        var node = {}
        // data
        node['id'] = table.getValueByName('ID')
        node['name'] = table.getValueByName('Name')
        node['text'] = table.getValueByName('Name')
        node['icon'] = 'folder'
        node['folder'] = true
        pnode.push(node)
        this.treeNodes = pnode
        nodeMap.set(node.id, node)
        table.next()
      }
      // 机器
      const { ids = '' } = this.params // 数据回显用
      table = new SQLTable(vPar.getTable('k_computer'))
      table.first()
      while (!table.eof()) {
        pnode = Global.getTreeviewPNode(nodeMap, nodes, table.getValueByName('GroupID'))
        node = {}
        // data
        node['id'] = table.getValueByName('ID')
        node['ip'] = table.getValueByName('IP')
        node['name'] = table.getValueByName('Name')
        node['text'] = Global.strFormat('{0} [{1}]', node.ip, node.name)
        node['icon'] = 'ip'
        pnode.push(node)
        if (ids.indexOf(node.ip) !== -1) {
          this.treeDefaultCheckedKeys.push(node.id)
        }
        table.next()
      }
      this.treeData = nodes
    })
  },
  methods: {
    confirm() {
      const nodes = this.$refs.tree.getCheckedNodes()
      const data = []
      for (let i = 0; i < nodes.length; i++) {
        if (this.params.ids.indexOf(nodes[i].ip) === -1 && !nodes[i].folder) {
          data.push(nodes[i])
        }
      }
      this.params.confirm(data)
    }
  }
}
</script>

<style scoped>
.box1 {
    /* border: red 1px solid; */
  height: 500px;
  overflow-y: auto;
  padding: 5px;
  /* 隐藏滚动条 */
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
}
.box1::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}
</style>
